package com.panda.handler.security;

import com.alibaba.fastjson.JSON;
import com.panda.enums.AppHttpCodeEnum;
import com.panda.utils.RespondResult;
import com.panda.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: panda
 * @Date: 2022-05-18 16:12
 * @Description: ？copy
 */

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //封装报错信息给前端
        RespondResult result = null;
        if (e instanceof BadCredentialsException) {
            result = RespondResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(), e.getMessage());
        } else if (e instanceof InsufficientAuthenticationException) {
            result = RespondResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else {
            result = RespondResult.errorResult(AppHttpCodeEnum.ERROR.getCode(), "认证或授权失败。");
        }
        //响应给前端
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
    }
}
